<template>
  <div class="about">
    <div class="head" ref="headHeight">
      <div class="logo">
        <div class="name">Admin about</div>
      </div>
      <Navbar :choseid=2 />
    </div>
    <div class="mainboby">
      <div class="menu" v-if="isfold" ref="menuHeight">
        <div class="content">
          <div class="content1">
            <span @click="dialogFormVisibleMethods({ id: 0 })">+</span>
            <el-input placeholder="Enter keywords to filter" v-model="filterText">
            </el-input>
          </div>
          <el-tree
            :data="data"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :props="defaultProps"
            @node-click="checkContent"
            ref="tree">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <i class="el-icon-edit" @click="editCategory(data)"></i>
                <i class="el-icon-minus" @click="deleteList(data.id)"></i>
                <i class="el-icon-plus" @click="dialogFormVisibleMethods(data)"></i>
                <!-- <el-button size="mini" @click="dialogFormVisibleMethods(data)">+</el-button>
                <el-button size="mini" @click="deleteList(data.id)">-</el-button> -->
              </span>
            </span>
          </el-tree>
        </div>
      </div>
      <div class="container">
        <div class="main" v-if="id">
          <el-tabs type="border-card" v-model="activeName">
            <el-tab-pane label="Content management" name="first">
              <div class="local-quill-editor">
                <quill-editor
                  ref="QuillEditor"
                  v-model="contentText"
                  :options="editorOption"
                  class="editor"
                  @change="onEditorChange">
                </quill-editor>
              </div>
              <div class="local_btn">
                <el-button plain @click="editContent">save</el-button>
              </div>
              
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="main_text" v-else>
          Contact & About
        </div>
      </div>
    </div>
    <el-dialog title="Add data" :visible.sync="dialogFormVisible">
      <el-form :model="form" status-icon :rules="rules" ref="fromName">
        <el-form-item label="name" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <!--<el-form-item label="排序" :label-width="formLabelWidth" prop="sort">
          <el-input v-model="form.sort" autocomplete="off"></el-input>
        </el-form-item>-->
        <el-form-item label="describe" :label-width="formLabelWidth" prop="mark">
          <el-input v-model="form.mark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">cancel</el-button>
        <el-button type="primary" @click="addCategory">submit</el-button>
      </div>
    </el-dialog>
    <!-- <el-dialog title="编辑数据" :visible.sync="dialogFormVisible2">
      <div class="local-quill-editor">
        <quill-editor
          ref="QuillEditor"
          v-model="content"
          :options="editorOption"
          class="editor"
          @change="onEditorChange"
        >
          >
        </quill-editor>
      </div>
      <el-button plain @click="editContent">save</el-button>
    </el-dialog> -->
    <el-upload
      id="upimg"
      v-show="false"
      class="upload-demo"
      :action="imgUploadUrl"
      :data="loadData"
      :on-success="handleSuccess"
      list-type="picture"
      multiple
    >
      <el-button size="small" type="primary">Click upload</el-button>
    </el-upload>
    <Footer/>
  </div>
</template>

<script>
// 工具栏配置项
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
  [{ header: 1 }, { header: 2 }], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{ script: "sub" }, { script: "super" }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  [{ indent: "-1" }, { indent: "+1" }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
  [{ direction: "rtl" }], // 文本方向-----[{'direction': 'rtl'}]
  [{ size: ["small", false, "large", "huge"] }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{ font: [] }], // 字体种类-----[{ font: [] }]
  [{ align: [] }], // 对齐方式-----[{ align: [] }]
  ["clean"], // 清除文本格式-----['clean']
  ["image", "video"], // 链接、图片、视频-----['link', 'image', 'video']
];

import Navbar from "../components/Navbar.vue";
import Footer from "../components/Footer.vue";

export default {
  components:{
    Navbar,
    Footer,
  },
  created() {
    this.getCategory();
  },
  data() {
    let validatename = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("Please enter the content. It cannot be blank"));
      } else {
        callback();
      }
    };
    let validatemark = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("Please enter the content. It cannot be blank"));
      } else {
        callback();
      }
    };
    let validatesort = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("Please enter the content. It cannot be blank"));
      } else {
        callback();
      }
    };
    return {
      imgUrl: null,
      imgUploadUrl: window.VUE_APP_BASE_URL + "uploadFile",
      loadData: {},
      title2: "",
      isMenu: true,
      rules: {
        name: [{ validator: validatename, trigger: "blur" }],
        mark: [{ validator: validatemark, trigger: "blur" }],
        sort: [{ validator: validatesort, trigger: "blur" }],
      },
      formLabelWidth: "70px",
      form: {
        name: "",
        //sort: "",
        mark: "",
      },
      dialogFormVisible: false,
      dialogFormVisible2: false,
      id: "",
      isfold: true,
      // content: "<img src:'http://192.168.84.168:9080/uploads/avatar(1).png'>",
      contentText: "",
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            placeholder: "Please enter the text",
            handlers: {
              image: function (value) {
                if (value) {
                  // 调用element的图片上传组件
                  // （这里是用的原生js的选择dom方法）
                  document.querySelector("#upimg button").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
      data: [],
      defaultProps: {
        children: "childList",
        label: "name",
      },
      filterText: "",
      activeName: "first",
      screenWidth: document.body.clientWidth,//浏览器显示的区域高度
      screenHeight: document.body.clientHeight,//浏览器显示的区域高度
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    id() {
      this.loadData = { ptype: 1, type: this.id };
    },
    /* 监听*/
    screenWidth(val) {//宽度变化时  实时更新编辑器高度
      // console.log(val,'screenWidth')
      let headHeight = Number(window.getComputedStyle(this.$refs.headHeight).height.replace(/[^0-9]/ig,""))
      let menuHeight = Number(window.getComputedStyle(this.$refs.menuHeight).height.replace(/[^0-9]/ig,""))
      this.screenWidth = val;
      if(!this.$refs.QuillEditor) return false
      if(this.screenWidth < 768 ){
        this.$refs.QuillEditor.$refs.editor.style.height = `${this.screenHeight-headHeight-menuHeight-160}px`
      }
    },
    screenHeight(val) {//高度变化时  实时更新编辑器高度
      // console.log(val,'screenHeight')
      let headHeight = Number(window.getComputedStyle(this.$refs.headHeight).height.replace(/[^0-9]/ig,""))
      let menuHeight = Number(window.getComputedStyle(this.$refs.headHeight).height.replace(/[^0-9]/ig,""))
      this.screenHeight = val;
      // 给quillEditor 重新赋值高度
      if(!this.$refs.QuillEditor) return false
      this.$refs.QuillEditor.$refs.editor.style.height = `${this.screenHeight-headHeight-menuHeight-230}px`
    }
  },
  mounted(){
    const that = this
    // 设置编辑器高度
    window.onresize= () => {
      return (() => {
        window.screenWidth = document.body.clientWidth;
        window.screenHeight = document.body.clientHeight;
        that.screenWidth = window.screenWidth;
        that.screenHeight = window.screenHeight;
      })();
    }
  },
  methods: {
    //对tree过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //点击+弹框与获取节点id
    dialogFormVisibleMethods(data) {
      this.dialogFormVisible = true;
      this.id = data.id;
    },
    //获取tree数据
    getCategory() {
      this.$api.default.AgetCategory().then((res) => {
        this.data = res.data;
        // this.$nextTick(()=>{ //默认选中首个元素
        // this.id = res.data[0].id;
        //   this.$refs.tree.setCurrentKey(res.data[0].id)
        // })
        
        // this.id = res.data[0].id;
      });
    },
    // 点击修改--编辑tree数据
    editCategory(data){
      this.$prompt('Edit content', {
        confirmButtonText: 'submit',
        cancelButtonText: 'cancel',
        inputValue:data.name
      }).then(({ value }) => {
        this.updateCategory(data,value)
      }).catch((error) => {
        this.$message({
          type: 'info',
          message: 'Cancel input'
        });       
      });
    },
    updateCategory(data,value){
      let todata = {}
      todata.id = data.id
      todata.name=value,
      this.$api.default.AupdateCategory(todata).then((res)=>{
        this.getCategory()//重新获取左列列表
        this.$message({
          type: 'success',
          message: 'Edit succeeded'
        });
      }).catch(error=>{
        console.log(error,'error')
      })
    },
    //添加tree数据
    addCategory() {
      this.$refs.fromName.validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          this.$api.default
            .AaddCategory({
              name: this.form.name,
              mark: this.form.mark,
              pid: this.id,
            })
            .then(() => {
              this.$message({
                message: "Added successfully",
                type: "success",
              });
              this.getCategory();
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //删除tree数据
    deleteList(id) {
      this.$confirm("This operation will permanently delete the file. Do you want to continue?", "Tips", {
        confirmButtonText: "submit",
        cancelButtonText: "cancel",
        type: "warning",
      })
        .then(() => {
          this.$api.default.AdeleteCategory(id).then(() => {
            this.getCategory();
            this.$message({
              type: "success",
              message: "Delete succeeded!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "Deletion cancelled",
          });
        });
    },
    //点击节点事件
    checkContent(data,node) {
      let that = this;
      if(node.isLeaf){
      this.id = data.id;
      this.$api.default
        .AcheckContent(data.id)
        .then((res) => {
          if (res.data !== null) {
            that.contentText = res.data.content;
          } else {
            that.contentText = "";
          }
        })
        .catch(() => {
          that.contentText = "";
          that.imgUrl = "";
        });
      }
    },
    //编辑内容
    editContent() {
      let that = this;
      this.$api.default
        .AeditContent({ content: this.contentText, id: that.id })
        .then(() => {
          this.$message({
            message:'Saved successfully',
            type:'success'
          })
          // that.dialogFormVisible2 = false;
        });
    },
    // element的upload组件上传图片成功后调用的函数
    handleSuccess(res) {
      // 获取富文本组件实例
      let quill = this.$refs.QuillEditor.quill;
      if (res) {
        // 如果上传成功
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, "image", window.VUE_APP_BASE_URL + res.data);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        // 提示信息
        this.$message.error("Picture insertion failed");
      }
    },

    //// 失去焦点事件
    //onEditorBlur(e) {
    //  console.log("onEditorBlur: ", e);
    //},
    //// 获得焦点事件
    //onEditorFocus(e) {
    //  console.log("onEditorFocus: ", e);
    //},
    // 内容改变事件
    onEditorChange(e) {
      //首次点击  编辑器赋值默认高度
      let screenHeight = document.body.clientHeight
      let headHeight = Number(window.getComputedStyle(this.$refs.headHeight).height.replace(/[^0-9]/ig,""))
      let menuHeight = Number(window.getComputedStyle(this.$refs.headHeight).height.replace(/[^0-9]/ig,""))
      this.$refs.QuillEditor.$refs.editor.style.height = `${screenHeight-headHeight-menuHeight-230}px`
      this.contentText = e.html;

    },
  },
};
</script>
<style scoped>

</style>
<style lang="scss" scoped>
.about {
  width: 100%;
  height: 100vh;
  overflow-y:scroll;
  position: relative;
  .head {
    width: 100%;
    display: flex;
    justify-content: space-between;
    .logo {
      height: 76px;
      background-color: #191a23;
      text-align: center;
      font-family: sans-serif;
      line-height: 1.15;
      color: #ebebec;
      font-size: 28px;
      font-weight: 200;
      line-height: 76px;
      border-bottom: solid 2px #101117;
      flex-basis: 400px;
    }
    .header {
      height: 76px;
      background: #191a23;
      padding-right: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex: 1;
      .fold {
        height: 100%;
        width: 55px;
        padding: 0 12px;
        line-height: 76px;
        i {
          font-size: 24px;
          color: #fff;
        }
      }
      .info {
        height: 100%;
        padding: 0 12px;
        line-height: 76px;
        display: flex;
        align-items: center;
        .tui {
          margin-left: 10px;
          font-size: 20px;
        }
        img {
          width: 30px;
          height: 30px;
          border-radius: 50%;
          margin-right: 10px;
        }
        span {
          font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
            Microsoft YaHei, "\5FAE\8F6F\96C5\9ED1", Arial, sans-serif;
          color: #fff;
        }
      }
    }
  }
  .mainboby {
    display: flex;
    justify-content: flex-start;
    align-items: inherit;
    height: calc(100% - 80px);
    overflow:hidden;
    .menu {
      width: 400px;
      min-height:calc(100vh - 152px);
      background-color: #191a23;
      .content {
        padding-top: 10px;
        padding-left: 24px;
        .content1 {
          padding: 0 24px 0 0;
          margin-bottom: 10px;
          display: flex;
          justify-content: center;
          span{
            color: #ebebec;
            margin-right: 10px;
            font-size: 26px;
            font-weight: 400;
            border:1px solid #ebebec;
            padding: 0;
            width: 40px;height: 40px;
            text-align: center;
            line-height: 36px;
            border-radius: 5px;
          }
          ::v-deep .el-input {
            flex: 1;
            height: 40px;
            border: #101117;
            .el-input__inner {
              background-color: #191a23;
              color: #ebebec;
            }
          }
          ::v-deep {
            .el-button {
              background-color: #191a23;
              color: #ebebec;
              margin-right: 10px;
            }
          }
        }
        ::v-deep {
          .el-tree {
            padding: 0 24px 0 0;
            background-color: #191a23;
            .el-tree-node__content {
              background-color: #191a23;
              height: 35px;
              .custom-tree-node {
                color: #b9b9bc;
                font-size: 14px;
                line-height: 1.5;
                padding-right: 6px;
                width: 100%;
                display: flex;
                justify-content: space-between;
                align-items: center;
                i{
                  margin-right: 5px;
                }
                .el-button {
                  // float: right;
                  width: 23px;
                  height: 23px;
                  padding: 0;
                  background: #191a23;
                  color: #fff;
                }
              }
            }
            .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  background-color: #409eff;
  color: white;
}
            // .el-tree-node__content {
            //   &:active{
            //     background-color: #303135;
            //   }
            // }
            // .el-tree-node__children {
            //   &:active{
            //     .el-tree-node__content {
            //       background-color: #303135;
            //     }
            //   }
            // }
          }
        }
      }
    }
    .container {
      flex: 1;
      position: relative;
      height: 100%;
      .main {
        margin: 10px;
        border: solid 1px #ddd;
        box-shadow: 0 0 5px rgba($color: #000000, $alpha: 0.3);
        .title {
          margin-bottom: 15px;
          padding-bottom: 10px;
          //border-bottom: 2px solid #e8eaec;
          height: 150px;
          display: flex;
          margin-right: 20px;

          span {
            flex-basis: 100px;
            padding-right: 10px;
            text-align: center;
          }
          .content {
            flex: 9;
            border: solid 1px #ddd;
          }
        }
        .photo {
          margin-bottom: 15px;
          padding-bottom: 10px;
          //border-bottom: 2px solid #e8eaec;
          height: 330px;
          display: flex;
          margin-right: 20px;

          span {
            flex-basis: 100px;
            padding-right: 10px;
            text-align: center;
          }
          .img {
            flex: 1;
            border: solid 1px #ddd;
            overflow: overlay;
          }
        }
        .local_btn{
          text-align: center;
        }
      }
      .main_text{
        color:#333;
        position: absolute;
        width: 100%;
        top:30%;
        left: 50%;
        transform: translate(-50%,-50%);
        text-align: center;
        font-size: 50px;
      }
      .bjBtn {
        margin-left: 50%;
        transform: translateX(-50px);
      }
    }
  }

  ::v-deep {
    .ql-editor {
      min-height: 200px;
    }
    .local-quill-editor {
      margin-bottom: 10px;
    }
  }
}
@media screen and (max-width: 768px) {
  .about {
    .mainboby{
      flex-direction: column;
      padding-bottom: 160px;
      .menu{
        width: 100%;
        height: auto;
        min-height: auto;
      }
      .container{
        margin-bottom: 10px;
        overflow-y: scroll;
        .main_text{
          top:50%;
        }
      }
    }
  }
}
</style>
